// pages/settle/settle.ts
import { UploadAPI, AuthAPI } from '../../utils/api'

interface SettlePageData {
  statusBarHeight: number;
  currentStep: number;
  
  // 基本信息
  merchantName: string;
  merchantType: number; // 1-个体工商户，2-企业
  contactName: string;
  contactPhone: string;
  email: string;
  address: string;
  description: string;
  remark: string; // 申请备注
  
  // 资质文件
  businessLicenseUrl: string;
  idCardFrontUrl: string;
  idCardBackUrl: string;
  otherCertificateUrl: string;
  
  // 协议
  agreed: boolean;
  
  // 申请结果
  applicationId: string;
  submitTime: string;
}

Page({
  data: {
    statusBarHeight: 0,
    currentStep: 1,
    
    merchantName: '',
    merchantType: 0,
    contactName: '',
    contactPhone: '',
    email: '',
    address: '',
    description: '',
    remark: '',
    
    businessLicenseUrl: '',
    idCardFrontUrl: '',
    idCardBackUrl: '',
    otherCertificateUrl: '',
    
    agreed: false,
    
    applicationId: '',
    submitTime: ''
  } as SettlePageData,

  onLoad() {
    const systemInfo = wx.getSystemInfoSync();
    const statusBarHeight = systemInfo.statusBarHeight || 0;
    
    this.setData({
      statusBarHeight
    });
  },

  // 返回
  goBack() {
    // 清除token和用户信息，避免自动登录
    wx.removeStorageSync('merchantToken');
    wx.removeStorageSync('merchantUserInfo');
    
    // 使用redirectTo返回登录页，避免navigateBack失败
    wx.redirectTo({
      url: '/pages/auth/auth'
    });
  },

  // 选择商家类型
  selectMerchantType(e: any) {
    const type = parseInt(e.currentTarget.dataset.type);
    this.setData({
      merchantType: type
    });
  },


  // 上传营业执照
  uploadBusinessLicense() {
    this.chooseAndUploadImage((url: string) => {
      this.setData({ businessLicenseUrl: url });
    });
  },

  // 上传身份证正面
  uploadIdCardFront() {
    this.chooseAndUploadImage((url: string) => {
      this.setData({ idCardFrontUrl: url });
    });
  },

  // 上传身份证反面
  uploadIdCardBack() {
    this.chooseAndUploadImage((url: string) => {
      this.setData({ idCardBackUrl: url });
    });
  },

  // 上传其他证件
  uploadOtherCertificate() {
    this.chooseAndUploadImage((url: string) => {
      this.setData({ otherCertificateUrl: url });
    });
  },

  // 选择并上传图片
  async chooseAndUploadImage(callback: (url: string) => void) {
    wx.chooseImage({
      count: 1,
      sizeType: ['compressed'],
      sourceType: ['album', 'camera'],
      success: async (res) => {
        const tempFilePath = res.tempFilePaths[0];
        
        wx.showLoading({ title: '上传中...', mask: true });
        
        try {
          // 使用统一的上传API
          const response = await UploadAPI.uploadFile(tempFilePath);
          console.log('结算页图片上传响应:', response);
          
          if (response.code === 200) {
            // 后端返回格式: { code: 200, msg: "操作成功", data: "https://xxx.com/xxx.png" }
            let fileUrl = '';
            if (response.data) {
              if (typeof response.data === 'string') {
                fileUrl = response.data;
              } else if (response.data.url) {
                fileUrl = response.data.url;
              } else if (response.data.fileUrl) {
                fileUrl = response.data.fileUrl;
              }
            }
            if (!fileUrl) {
              fileUrl = response.url || tempFilePath;
            }
            console.log('结算页图片最终URL:', fileUrl);
            callback(fileUrl);
            wx.showToast({ title: '上传成功', icon: 'success' });
          } else {
            wx.showToast({ title: response.msg || '上传失败', icon: 'none' });
          }
        } catch (error) {
          console.error('上传失败:', error);
          wx.showToast({ title: '上传失败', icon: 'none' });
        } finally {
          wx.hideLoading();
        }
      }
    });
  },

  // 提交申请
  async submitApplication() {
    const { 
      merchantName, 
      merchantType, 
      contactName, 
      contactPhone, 
      email, 
      address, 
      description,
      businessLicenseUrl, 
      idCardFrontUrl, 
      idCardBackUrl, 
      agreed 
    } = this.data;
    
    // 验证基本信息
    if (!merchantName.trim()) {
      wx.showToast({ title: '请输入商家名称', icon: 'none' });
      return;
    }
    
    if (merchantType === 0) {
      wx.showToast({ title: '请选择商家类型', icon: 'none' });
      return;
    }
    
    if (!contactName.trim()) {
      wx.showToast({ title: '请输入联系人姓名', icon: 'none' });
      return;
    }
    
    if (!this.validatePhone(contactPhone)) {
      wx.showToast({ title: '请输入正确的联系电话', icon: 'none' });
      return;
    }
    
    if (!email.trim()) {
      wx.showToast({ title: '请输入邮箱地址', icon: 'none' });
      return;
    }
    
    if (!address.trim()) {
      wx.showToast({ title: '请输入商家地址', icon: 'none' });
      return;
    }
    
    if (!businessLicenseUrl) {
      wx.showToast({ title: '请上传营业执照', icon: 'none' });
      return;
    }
    
    if (!idCardFrontUrl) {
      wx.showToast({ title: '请上传身份证正面', icon: 'none' });
      return;
    }
    
    if (!idCardBackUrl) {
      wx.showToast({ title: '请上传身份证反面', icon: 'none' });
      return;
    }
    
    if (!agreed) {
      wx.showToast({ title: '请先阅读并同意相关协议', icon: 'none' });
      return;
    }

    wx.showLoading({ title: '提交中...', mask: true });

    try {
      // 准备请求数据，字段名匹配后端API
      const requestData = {
        merchantName,
        merchantType,
        contactName,
        contactPhone,
        contactEmail: email,
        address,
        description: description || '',
        businessLicense: businessLicenseUrl,
        idCardFront: idCardFrontUrl,
        idCardBack: idCardBackUrl,
        otherCredentials: this.data.otherCertificateUrl ? [this.data.otherCertificateUrl] : [],
        agreeAgreement: agreed,
        remark: this.data.remark || '' // 添加备注字段
      };
      
      // 调试日志：输出提交的数据
      console.log('=== 提交入驻申请 ===');
      console.log('请求数据:', requestData);
      console.log('==================');
      
      // 使用AuthAPI提交申请
      const response = await AuthAPI.submitApplication(requestData);
      
      wx.hideLoading();
      
      if (response.code === 200) {
        // 提交成功，显示成功信息并跳转到审核状态页面
        wx.showModal({
          title: '提交成功',
          content: '您的入驻申请已提交成功，平台将在1-3个工作日内完成审核。',
          showCancel: false,
          confirmText: '知道了',
          success: () => {
            // 跳转到审核状态页面
            wx.redirectTo({
              url: '/pages/audit-status/audit-status'
            });
          }
        });
      } else {
        wx.showToast({ 
          title: response.msg || '提交失败', 
          icon: 'none' 
        });
      }
    } catch (error: any) {
      wx.hideLoading();
      console.error('提交失败:', error);
      wx.showToast({ 
        title: error.msg || '提交失败，请重试', 
        icon: 'none' 
      });
    }
  },

  // 返回登录
  backToLogin() {
    // 清除token和用户信息，避免自动登录
    wx.removeStorageSync('merchantToken');
    wx.removeStorageSync('merchantUserInfo');
    
    wx.redirectTo({
      url: '/pages/auth/auth'
    });
  },

  // 查看协议
  viewProtocol(e: any) {
    const type = e.currentTarget.dataset.type;
    let title = '协议';
    if (type === 'settle') title = '商家入驻协议';
    else if (type === 'service') title = '服务条款';
    else if (type === 'privacy') title = '隐私政策';
    
    wx.showModal({
      title: title,
      content: '这里是协议内容...',
      showCancel: false
    });
  },

  // 验证手机号
  validatePhone(phone: string): boolean {
    const phoneRegex = /^1[3-9]\d{9}$/;
    return phoneRegex.test(phone);
  },

  // 表单输入处理
  onMerchantNameInput(e: any) {
    this.setData({ merchantName: e.detail.value });
  },
  
  onContactNameInput(e: any) {
    this.setData({ contactName: e.detail.value });
  },
  
  onContactPhoneInput(e: any) {
    this.setData({ contactPhone: e.detail.value });
  },
  
  onEmailInput(e: any) {
    this.setData({ email: e.detail.value });
  },
  
  onAddressInput(e: any) {
    this.setData({ address: e.detail.value });
  },
  
  onDescriptionInput(e: any) {
    this.setData({ description: e.detail.value });
  },
  
  onRemarkInput(e: any) {
    this.setData({ remark: e.detail.value });
  },
  
  onAgreeChange(e: any) {
    this.setData({
      agreed: e.detail.value.includes('agree')
    });
  }
});
